//
//  CollectionTableViewController.swift
//  NewsAPP
//
//  Created by URNing B on 2021/5/26.
//

import UIKit

protocol AddCollectionNews {
    func addNews()
}


class CollectionTableViewController: UITableViewController, AddCollectionNews {
    
    var searchcontroller : UISearchController!
    
    override func viewDidLoad() {
        tableView.rowHeight = 130

        super.viewDidLoad()
        
        initSearch()
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
    }

    func addNews() {
        if DBControl.CollectionCount == 0
        {
            navigationController?.tabBarItem.badgeValue = nil
        }
        else
        {
            navigationController?.tabBarItem.badgeValue = "\(DBControl.CollectionCount)"
        }
    }
    
    func initSearch()
    {
        let resultController = SearchResultTableViewController()
        searchcontroller = UISearchController(searchResultsController: resultController)
        let searchBar = searchcontroller.searchBar
        searchBar.placeholder = "Enter a search item"
        searchBar.sizeToFit()
        tableView.tableHeaderView = searchBar
        searchcontroller.searchResultsUpdater = resultController
        self.definesPresentationContext = true
    }
    // MARK: - Table view data source


    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let sqlite = SQLiteManager.sharedInstance

        if !sqlite.openDB(){return 0}

        //let queryResult = sqlite.execQuerySQL(sql: "SELECT * FROM CollectionNews")
        if DBControl.CollectionCount == 0
        {
            navigationController?.tabBarItem.badgeValue = nil
        }
        else
        {
            navigationController?.tabBarItem.badgeValue = "\(DBControl.CollectionCount)"
        }
        //print(queryResult!.count)
        return DBControl.CollectionCount
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Collectioncell", for: indexPath) as! CollectionTableViewCell
        
        let newsId = indexPath.row + 1
        cell.CollectionNewsTitle.text! = DBControl.getCollectionNewsTitle(id: newsId)
        cell.CollectionNewsTime.text! = DBControl.getCollectionNewsTime(id: newsId)
        let urlNet = URL(string: DBControl.getCollectionNewsImage(id: newsId))
        let task = URLSession.shared.dataTask(with: urlNet!)
        {
            (data,respones,error)in
            if let nsd = data{
                DispatchQueue.main.async {
                    cell.CollectionNewsImage.image = UIImage(data: nsd)
                }
            }
        }
        task.resume()

        // Configure the cell...

        return cell
    }
    
    override func viewWillAppear(_ animated: Bool) {
        tableView.reloadData()
    }
    
    
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    

    
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            
            DBControl.deleteCollectionNews(id: indexPath.row + 1)
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
            
        }
        if DBControl.CollectionCount == 0
        {
            navigationController?.tabBarItem.badgeValue = nil
        }
        else
        {
            navigationController?.tabBarItem.badgeValue = "\(DBControl.CollectionCount)"
        }
        print(DBControl.CollectionCount)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let dest = segue.destination as? CollectionDetailViewController
        {
            dest.newsPath = DBControl.getCollectionNewsPath(id: tableView.indexPathForSelectedRow!.row + 1)
        }
    }
    

}
